<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 栅格布局 -->
      <el-row :gutter="20">
          <el-col :span="8">
              <!-- 搜索栏 -->
              <el-input placeholder="请输入内容" v-model="queryParams.query" clearable @clear="getUsersTableList">
                <el-button slot="append" icon="el-icon-search" @click="getUsersTableList"></el-button>
              </el-input>
          </el-col>
          <el-col :span="4">
              <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
          </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table
        stripe
        border
        :data="usersTableList"
        style="width: 100%">
        <el-table-column type="index">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
            <template slot-scope="scope">
                <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
            <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
                <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRolehandle(scope.row)"></el-button>
                </el-tooltip>
            </template>
        </el-table-column>
      </el-table>
      <!-- 分页部分 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryParams.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 添加用户的对话框 -->
    <el-dialog
      @close="closeAddUserDialog"
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="50%">
      <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserDialogHandle">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息的对话框 -->
    <el-dialog
      @close="closeEditUser"
      title="修改用户信息"
      :visible.sync="editUserDialogVisible"
      width="50%">
      <el-form :model="editUserRuleForm" :rules="editUserRules" ref="editUserRuleFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserRuleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserDialogHandle">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="resetRoleSelect">
      <p>姓名: {{setRoleSelectedInfo.username}}</p>
      <p>当前角色: {{setRoleSelectedInfo.role_name}}</p>
      <p>分配角色:
        <el-select v-model="setRoleInfo" placeholder="请选择">
          <el-option
            v-for="item in allRoles"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitNewRole">确 定</el-button>
      </span>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data () {
    var checkEmail = (rule, value, callback) => {
      const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }

    var checkmobile = (rule, value, callback) => {
      const reg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      queryParams: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      usersTableList: [],
      total: 0,
      // 添加用户对话框的展示与隐藏
      addUserDialogVisible: false,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 修稿用户信息对话框的展示与隐藏
      editUserDialogVisible: false,
      // 修改用户信息的表单
      editUserRuleForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色的显示与隐藏
      setRoleDialogVisible: false,
      // 分配角色中的被选中人信息
      setRoleSelectedInfo: {},
      // 分配角色中的下拉菜单获取的值
      setRoleInfo: {},
      allRoles: '',
      // 需要设置角色的用户id
      submitSetRoleUserId: ''
    }
  },
  methods: {
    // 获取数据渲染页面
    async getUsersTableList () {
      const { data: res } = await this.$http.get('users', { params: this.queryParams })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.usersTableList = (res.data.users)
      this.total = res.data.total
    },
    // 监听每页显示数据条数的变化
    handleSizeChange (newSize) {
      this.queryParams.pagesize = newSize
      this.getUsersTableList()
    },
    // 监听页码的变化
    handleCurrentChange (newPage) {
      this.queryParams.pagenum = newPage
      this.getUsersTableList()
    },
    // 改变用户状态事件
    async userStateChange (userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('修改用户状态成功')
    },
    // 关闭添加用户对话框事件
    closeAddUserDialog () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 添加用户对话框的预验证以及提交数据以及渲染页面
    addUserDialogHandle () {
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请完善用户信息')
        const { data: res } = await this.$http.post('users', this.addUserForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.error('添加用户成功')
        this.addUserDialogVisible = false
        this.getUsersTableList()
      })
    },
    // 编辑用户信息
    editUser (info) {
      console.log(info)
      this.editUserRuleForm.username = info.username
      this.editUserRuleForm.id = info.id
      this.editUserRuleForm.email = info.email
      this.editUserRuleForm.mobile = info.mobile
      this.editUserDialogVisible = true
    },
    // 关闭编辑用户信息对话框的事件
    closeEditUser () {
      this.$refs.editUserRuleFormRef.resetFields()
    },
    // 修改用户信息提交信息并重新渲染页面
    editUserDialogHandle () {
      this.$refs.editUserRuleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请正确修改用户信息')
        const { data: res } = await this.$http.put('users/' + this.editUserRuleForm.id, this.editUserRuleForm)
        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功')
        this.editUserDialogVisible = false
        this.getUsersTableList()
      })
    },
    // 删除用户
    async removeUser (id) {
      const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'cancel') return this.$message.info('已取消删除')
      const delres = await this.$http.delete('users/' + id)
      console.log(delres)
      if (delres.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUsersTableList()
    },
    // 分配角色按钮的相关事件
    async setRolehandle (info) {
      this.submitSetRoleUserId = info.id
      this.setRoleSelectedInfo.username = info.username
      this.setRoleSelectedInfo.role_name = info.role_name
      this.setRoleDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分配角色的列表失败')
      }
      this.allRoles = res.data
    },
    // 分配角色对话框关闭事件
    resetRoleSelect () {
      this.setRoleInfo = ''
    },
    // 提交分配的角色到数据库
    async submitNewRole () {
      if (!this.setRoleInfo) return this.$message.error('请选择分配的角色')
      const { data: res } = await this.$http.put(`users/${this.submitSetRoleUserId}/role`, { rid: this.setRoleInfo })
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('分配角色成功')
      this.getUsersTableList()
      this.setRoleDialogVisible = false
    }
  },
  mounted () {
    this.getUsersTableList()
  }
}
</script>

<style>

</style>
